<template>
  <AuModal
    v-model="showTreePopup"
    title="下发版本"
    width="600px"
    :padding="false"
    @handleConfirm="handleTreeConfirm"
    @close="handleTreeClose"
  >
    <div
      class="flex flex-col py-[30px] px-[16px] text-[--autata-font-gray2-color]"
    >
      <div class="flex">
        <div class="label flex-grow leading-[30px] text-right pr-[20px]">
          门店/设备列表
        </div>
        <div class="w-[440px]">
          <!--          <el-input-->
          <!--            v-model="query"-->
          <!--            placeholder="请输入筛选条件"-->
          <!--            @input="onQueryChanged"-->
          <!--          />-->
          <vxe-card
            v-loading="loading"
            class="w-full mt-2 py-[8px] h-[330px]"
            :padding="false"
          >
            <el-tree-v2
              ref="treeRef"
              :data="treeData"
              :props="treeProps"
              :filter-method="filterMethod"
              :default-expanded-keys="expandedKeys"
              :item-size="38"
              show-checkbox
              :height="320"
            />
          </vxe-card>
          <!--          <el-tree-select-->
          <!--            ref="treeRef"-->
          <!--            v-model="checkedData"-->
          <!--            :data="treeData"-->
          <!--            :props="treeProps"-->
          <!--            value-key="id"-->
          <!--            multiple-->
          <!--            :render-after-expand="false"-->
          <!--            show-checkbox-->
          <!--            style="width: 100%"-->
          <!--          />-->
        </div>
      </div>
      <div class="flex mt-[20px]">
        <div class="label flex-grow leading-[30px] text-right pr-[20px]">
          备注
        </div>
        <div class="w-[440px]">
          <el-input
            v-model="note"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </div>
      </div>
    </div>
  </AuModal>
</template>

<script setup lang="ts">
import { computed, ref, toRef, watch } from "vue";
import { ElTreeV2, ElMessage } from "element-plus";
import type {
  TreeKey,
  TreeNode
} from "element-plus/es/components/tree-v2/src/types";
import { getReleaseSelect, TreeProp } from "@/api/teaInfuser/formula";

import { VxeUI } from "vxe-table";
import { AuModal } from "@/components/AuModal";
import {
  formulaVersionGetRelease,
  formulaVersionRelease
} from "@/api/cabinet/formulaVersion";

defineOptions({
  name: "IssueModal"
});

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  versionId: {
    type: [Number, String]
  }
});
const emit = defineEmits(["update:modelValue"]);

const showTreePopup = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const query = ref("");
const note = ref("");
const loading = ref(false);
const expandedKeys = ref<TreeKey[]>([]);
let flatKeys = [];
const treeData = ref<TreeProp[]>([]);
const treeProps = {
  value: "id",
  label: "name",
  class: "custom-node",
  children: "children"
};
const checkedData = ref([]);
const treeRef = ref<InstanceType<typeof ElTreeV2>>();

function transformData(data: TreeProp[]) {
  // flatKeys = [];
  return data.map(group => {
    let transformedGroup = {
      id: group.id,
      name: group.name,
      label: group.name,
      deviceId: group.name,
      type: group.parent_id ? "group" : group.type,
      disabled: false,
      children: group.children ? [...group.children] : []
    };
    flatKeys.push({
      id: group.id,
      name: group.name
    });
    expandedKeys.value.push(group.id);
    // 将门店的 device_list 合并到 store 对象中作为子节点
    if (group.store_list && group.store_list.length > 0) {
      group.store_list.forEach(store => {
        flatKeys.push({
          id: store.id,
          name: store.name
        });
        let storeWithDevices = {
          id: store.id,
          name: store.name,
          label: store.name,
          deviceId: store.name,
          type: "store"
          // children: store.device_list.map(device => {
          //   flatKeys.push({
          //     id: device.device_id,
          //     name: device.device_id
          //   });
          //   return {
          //     id: device.device_id,
          //     name: device.device_id,
          //     label: device.device_id,
          //     deviceId: device.device_id,
          //     type: "device",
          //     device_status: device.device_status,
          //     children: []
          //   };
          // })
        };
        transformedGroup.children.push(storeWithDevices as any);
      });
    } else {
      // if (
      //   !transformedGroup.children?.length &&
      //   transformedGroup.type !== "device"
      // ) {
      //   transformedGroup.disabled = true;
      // }
    }

    // 递归处理 children 中的数据
    if (transformedGroup.children && transformedGroup.children.length > 0) {
      transformedGroup.children = transformData(transformedGroup.children);
    }

    return transformedGroup as any;
  });
}

const getTreeData = async () => {
  loading.value = true;
  try {
    const res = await getReleaseSelect();
    if (res.code === 200) {
      treeData.value = transformData(res.data);
      treeRef.value!?.setExpandedKeys(expandedKeys.value);
      loading.value = false;

      const listRes = await formulaVersionGetRelease({
        idList: JSON.stringify([
          {
            id: props.versionId
          }
        ])
      });
      if (listRes.code === 200 && listRes.data?.length > 0) {
        note.value = listRes.data[0].note;
        const devices = listRes.data.map(v => v.store_id);
        // const keys = flatKeys
        //   .filter(v => devices.includes(v.name))
        //   .map(v => v.id);
        treeRef.value!.setCheckedKeys(devices);
      }
    }
  } catch (e) {
    console.log(e);
    loading.value = false;
  }
};

function hasChinese(text) {
  const reg = /[\u4e00-\u9fff]/;
  return reg.test(text);
}

const onQueryChanged = (query: string) => {
  treeRef.value!.filter(query);
};

const handleTreeConfirm = () => {
  const checkedNodes = treeRef.value!.getCheckedNodes();
  const sourceArray = [];
  // if (checkedNodes.length == 0) {
  //   sourceArray.push({ device_id: "0" });
  // }
  console.log(checkedNodes);
  checkedNodes.forEach(item => {
    if (item.type === "store") {
      // 根据要求的格式构造新对象，并添加到新数组中
      sourceArray.push({ store_id: String(item.id) });
    }
  });

  const param = JSON.stringify([
    {
      version: props.versionId,
      storeIdList: sourceArray, // 注意：这里根据实际需求可能不需要JSON.stringify
      note: note.value
    }
  ]);

  console.log(param);

  formulaVersionRelease({
    formulaList: param,
    is_auto: false,
    hiddenDeviceType: true
  }).then(res => {
    if (res.code === 200) {
      //VxeUI.modal.message({ content: "操作成功", status: "success" });
      // for (const checkedNode of checkedNodes) {
      //   treeRef.value!.setChecked(checkedNode.id, false);
      // }
      emit("update:modelValue", false);
      ElMessage({
        message: "下发成功",
        grouping: true,
        type: "success"
      });
    }
  });
};

const handleTreeClose = () => {
  const checkedNodes = treeRef.value!.getCheckedNodes();
  for (const checkedNode of checkedNodes) {
    treeRef.value!.setChecked(checkedNode.id, false);
  }
  emit("update:modelValue", false);
};

const filterMethod = (query: string, node: TreeNode) => {
  return node[treeProps.label]!.includes(query);
};

watch([() => props.modelValue, () => props.versionId], (val, id) => {
  checkedData.value = [];
  if (val) {
    getTreeData();
  }
});
</script>

<style lang="scss">
.custom-node {
  .el-tree-node__content {
    --el-checkbox-height: 38px;
  }
}
</style>
